/* api */
import { getRelationModifyProductList, batchEditProductType , checkRelatedServiceItem} from '@src/api/ProductV2Api'
/* service */
import { isQualityRuleField, isQualityRuleStartTimeField, isQualityTimeField } from '@service/FieldService.ts'
import { convertFormQualityRuleFieldValueToQualityRuleRemoteData } from '@service/QualityRuleService.ts'
/* util */
import { isEmpty } from '@src/util/type'
import Platform from '@src/util/platform.ts'

/**
 * @description 做成mixin没有任何意义，只是为了文件分离
 */
export default {
  name: 'product-quality-mixin',
  data() {
    return {
      qualityRuleFormData: {}
    }
  },
  computed: {
    /**
     * @description: 是否含有质保规则字段
     * @return {boolean}
     */
    isHaveQualityRuleField() {
      return this.fields.some(field => isQualityRuleField(field))
    }
  },
  methods: {
    // 参数处理 type save批量编辑保存 check 校验质保
    buildBatchEditParams(type) {
      const { form, selectedField } = this.$refs.batchForm.returnData()
      let fieldName = selectedField.fieldName
      let fieldValue = form[selectedField.fieldName]
      let otherValue = null
      const params = {
        ids: this.selectedIds,
        flag: false,
      }
      
      // 质保规则 质保起算时间字段
      if (isQualityRuleStartTimeField(selectedField)) {
        fieldName = 'qualityStartDate'
      }
      
      if (fieldName == 'pathName') {
        fieldName = 'parentId'
        fieldValue = (fieldValue.length && fieldValue[fieldValue.length - 1]) || ''
        // fieldValue = fieldValue?.[0] || ''
      }
      
      // 质保规则 质保时长字段
      if (isQualityTimeField(selectedField)) {
        let qualityRuleTimeValue = convertFormQualityRuleFieldValueToQualityRuleRemoteData(form)
        fieldName = type === 'save' ? 'qualityDuration' : 'qualityEndTime'
        fieldValue = qualityRuleTimeValue.qualityDuration
        otherValue = qualityRuleTimeValue.qualityUnit
      }
      
      params.changeList = [{
        fieldName,
        fieldValue,
        otherValue
      }]
      
      return params
    },
    batchEditSubmitBeforeHandler() {
      const isBatchEditHaveQualityTimeField = isQualityTimeField(this.$refs?.batchForm?.selectedField || {})
      const isBatchEditHaveQualityStartTimeField = isQualityRuleStartTimeField(this.$refs?.batchForm?.selectedField || {})
      if (isBatchEditHaveQualityTimeField || isBatchEditHaveQualityStartTimeField) {
        return this.productTypeRelationModifyHandler()
      }
      
      this.batchEditSubmit()
    },
    batchEditSubmit() {      
      const params = this.buildBatchEditParams('save')
      this.pending = true
      batchEditProductType(params)
        .then(res => {
          const isSuccess = res.success
          
          this.pending = false;
          this.$platform.notification({
            type: isSuccess ? 'success' : 'error',
            title: isSuccess ? this.$t('common.base.success') : this.$t('common.base.fail'),
            // title: `批量编辑产品类型${isSuccess ? '成功' : '失败'}`,
            message: isSuccess ? null : res.message
          });
          
          if (!isSuccess) return
          
          this.visible = false
          this.callback && this.callback();
          
        })
        .catch(error => {
          console.warn(error)
        })
        
    },
    getQualityChangedFieldNames() {
      let changedFieldNames = []
      let oldQualityRuleValue = this.productMenuValue || {}
      let newQualityRuleValue = this.productMenuValue?.qualityRule || {}

      // 质保起算时间
      if (oldQualityRuleValue.qualityStartDate != newQualityRuleValue.qualityStartTime) {
        changedFieldNames = changedFieldNames.concat([{
          fieldName: 'qualityStartDate',
          fieldValue: newQualityRuleValue.qualityStartTime
        }])
      } 

      // 质保时长
      if (
        oldQualityRuleValue.qualityDuration != newQualityRuleValue?.qualityTime?.qualityTimeNumber
        || oldQualityRuleValue.qualityUnit != newQualityRuleValue?.qualityTime?.qualityTimeType) {
        changedFieldNames = changedFieldNames.concat([{
          fieldName: 'qualityEndTime',
          fieldValue: newQualityRuleValue?.qualityTime?.qualityTimeNumber,
          otherValue: newQualityRuleValue?.qualityTime?.qualityTimeType
        }])
      }

      return changedFieldNames
    },

    async productTypeRelationModifyHandler() {
      
      const { changeList, ids } = this.buildBatchEditParams('check')

      // 查询是否有关联受到影响的产品
      let params = {
        cateLogId: ids,
        changeList: changeList
      }
      
      let relationProductResult = await getRelationModifyProductList(params)
      let isSuccess = relationProductResult?.success
      let relationProductList = relationProductResult?.result?.list || []
      
      // 查询失败或关联影响的产品列表为空 或质保起算时间是自定义的
      if (!isSuccess || isEmpty(relationProductList)) {
        return this.batchEditSubmit()
      }

      const { form } = this.$refs.batchForm.returnData()
      this.qualityRuleFormData = form
      // 显示关联影响弹窗
      this.$refs?.BizProductTypeRelationModifyDialog.outsideShow(params)
    },
    // 保存产品类型
    async submitWithEditAndQuality() {
      try {
        // 校验
        const validated = await this.$refs.form.validate(false)
        if (!validated) return Promise.reject('validate fail.')
        
        // 非编辑模式且没有质保规则字段 则直接提交
        if (!this.id && !this.isHaveQualityRuleField) {
          return this.submit()
        }
        // 编辑时校验产品类型关联的服务项目是否将被删掉
        if(this.id) {
          let relatedParams = {
            id: this.id,
            relatedServiceItem: this.productMenuValue?.relatedServiceItem || [],
          }
          const checkRes = await checkRelatedServiceItem(relatedParams)
          if ( checkRes.success && checkRes.result.flag ){
            const removeServiceItem =  checkRes.result.removeServiceItem || '';

            let confirm = await await this.$platform.confirm(this.$t('common.form.tip.relatedServiceItem.tip3', { removeServiceItem }));
            if(!confirm) return;
          }
        }
        
        let relationFieldNames = this.getQualityChangedFieldNames()
        if (isEmpty(relationFieldNames)) {
          return this.submit()
        }

        // 查询是否有关联受到影响的产品
        let params = {
          cateLogId: [this.id], 
          changeList: relationFieldNames,
        }

        let relationProductResult = await getRelationModifyProductList(params)
        let isSuccess = relationProductResult?.success
        let relationProductList = relationProductResult?.result?.list || []
        // 查询失败或关联影响的产品列表为空
        if (!isSuccess || isEmpty(relationProductList)) {
          return this.submit()
        }
        
        // 显示关联影响弹窗
        this.$refs?.BizProductTypeRelationModifyDialog.outsideShow(params)
        
      } catch (error) {
        console.warn(error)
      }
      
    },
    // 同步修改
    onBatchModifyProductTypeSuccessHandler(result) {
      this.visible = false;
      this.callback && this.callback();
      Platform.notificationForBase(result, this.$t('common.base.tip.batchModifyProductType'))
    }
  }
}